package com.leetcode.test.hash;

import org.junit.Assert;
import org.junit.Test;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * https://leetcode-cn.com/explore/learn/card/hash-table/204/practical-application-hash-set/807/
 * <p>
 * 解题：https://leetcode-cn.com/problems/intersection-of-two-arrays/solution/liang-ge-shu-zu-de-jiao-ji-by-leetcode/
 */
public class 两个数组的交集 {

	@Test
	public void test() {
		int[] nums1 = new int[]{1, 2, 2, 1};
		int[] nums2 = new int[]{2, 2};

		System.out.println(intersection(nums1, nums2));
	}

	@Test
	public void test2() {
		int[] nums1 = new int[]{4, 9, 5};
		int[] nums2 = new int[]{9, 4, 9, 8, 4};

		System.out.println(intersection(nums1, nums2));
	}

	public int[] intersection(int[] nums1, int[] nums2) {
		HashSet<Integer> set1 = new HashSet<>();
		for (Integer n : nums1) set1.add(n);
		HashSet<Integer> set2 = new HashSet<>();
		for (Integer n : nums2) set2.add(n);

		set1.retainAll(set2);

		int[] output = new int[set1.size()];
		int   idx    = 0;
		for (int s : set1) {
			output[idx++] = s;
		}
		return output;
	}

	private Set<Integer> toSet(int[] array) {
		Set<Integer> set = new HashSet<>();

		for (int val : array) {
			set.add(val);
		}
		return set;
	}
}
